package com.sk.weichat.ui.message.search;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.SearchContactAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.EditBaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.nearby.UserListGatherActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 搜索联系人
 */
public class SearchContactActivity extends EditBaseActivity implements View.OnClickListener {

    private LinearLayout ll_layout_search_empty;

    private ImageView iv_title_left;
    private EditText et_search_user;
    private ImageView iv_clear_user;
    private TextView tv_finish_search_user;
    private LinearLayout linear_search_tip;
    private TextView tv_search_text;
    //好友
    private LinearLayout ll_friends;
    private RecyclerView recy_friends;
    private String mLoginUserId;
    private List<Friend> mFriendList = new ArrayList<>();//好友列表
    private SearchContactAdapter mAdapter;

    //关注
    private LinearLayout ll_attention;
    private RecyclerView recy_attention;
    private List<Friend> mAttentionList = new ArrayList<>();//关注列表
    private SearchContactAdapter mAttentionAdapter;

    private String search_more;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_contact);
        getSupportActionBar().hide();
        mLoginUserId = coreManager.getSelf().getUserId();
        initView();
        initRecycerView();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initView() {
        ll_layout_search_empty = findViewById(R.id.ll_layout_search_empty);

        iv_title_left = findViewById(R.id.iv_title_left);
        et_search_user = findViewById(R.id.et_search_user);
        iv_clear_user = findViewById(R.id.iv_clear_user);
        tv_finish_search_user = findViewById(R.id.tv_finish_search_user);

        linear_search_tip = findViewById(R.id.linear_search_tip);
        tv_search_text = findViewById(R.id.tv_search_text);

        iv_title_left.setOnClickListener(this);
        iv_clear_user.setOnClickListener(this);
        tv_finish_search_user.setOnClickListener(this);
        linear_search_tip.setOnClickListener(this);
        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        et_search_user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    iv_clear_user.setVisibility(View.INVISIBLE);
                    ll_layout_search_empty.setVisibility(View.GONE);
                    linear_search_tip.setVisibility(View.GONE);
                    clearData();
                    return;
                }
                iv_clear_user.setVisibility(View.VISIBLE);
                linear_search_tip.setVisibility(View.VISIBLE);
                String tipStr = "搜索用户：<font color='#8d76fe'>" + s + "</font>";
                tv_search_text.setText(Html.fromHtml(tipStr));
                mAdapter.setKeyword(s.toString());
                mAttentionAdapter.setKeyword(s.toString());
                SearchContact();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_search_user.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (TextUtils.isEmpty(et_search_user.getText().toString())) {
                        ToastUtil.showToast(SearchContactActivity.this, "请输入搜索内容");
                        return true;
                    }
                    SearchContact();
                    return true;
                }
                return false;
            }
        });


        /*延迟加载 等待控件初始化*/
        new Handler().postDelayed(new Runnable() {
            public void run() {
                search_more = getIntent().getStringExtra("search_more");
                if (!TextUtils.isEmpty(search_more)) {
                    et_search_user.setText(search_more);
                    et_search_user.setSelection(search_more.length());
                    SearchContact();
                }
            }
        }, 50);
    }

    private void initRecycerView() {
        //好友
        ll_friends = findViewById(R.id.ll_friends);
        recy_friends = findViewById(R.id.recy_friends);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_friends.setLayoutManager(manager);
        mAdapter = new SearchContactAdapter(mFriendList);
        mAdapter.setHasStableIds(true);
        recy_friends.setNestedScrollingEnabled(true);
        recy_friends.setAdapter(mAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_friends.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mFriendList.get(position);
                if (view.getId() == R.id.img_search_avatar) {
                    Intent intent = new Intent(SearchContactActivity.this, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(SearchContactActivity.this, ChatActivity.class);
                    intent.putExtra(ChatActivity.FRIEND, friend);
                    intent.putExtra(Constants.NEW_MSG_NUMBER, friend.getUnReadNum());
                    startActivity(intent);
                }
            }
        });
        // 关注
        ll_attention = findViewById(R.id.ll_attention);
        recy_attention = findViewById(R.id.recy_attention);
        LinearLayoutManager manager1 = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_attention.setLayoutManager(manager1);
        mAttentionAdapter = new SearchContactAdapter(mAttentionList);
        mAttentionAdapter.setHasStableIds(true);
        recy_attention.setNestedScrollingEnabled(true);
        recy_attention.setAdapter(mAttentionAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_attention.getItemAnimator()).setSupportsChangeAnimations(false);
        mAttentionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mAttentionList.get(position);
                Intent intent = new Intent(SearchContactActivity.this, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == iv_title_left) {
            finish();
        } else if (v == tv_finish_search_user) {
            EventBus.getDefault().post("cancle");
        } else if (v == iv_clear_user) {
            et_search_user.setText("");
        } else if (v == linear_search_tip) {
            startActivity(new Intent(this, UserListGatherActivity.class).putExtra("search_user", et_search_user.getText().toString()));
        }
    }

    private void SearchContact() {
        List<Friend> datas = FriendDao.getInstance().QuearyFriends(mLoginUserId, et_search_user.getText().toString());//查找好友和关注 列表
        if (datas != null && datas.size() > 0) {
            mFriendList.clear();
            mAttentionList.clear();
            for (Friend friend : datas) {
                if (friend.getStatus() == Friend.STATUS_ATTENTION) {//我的关注列表
                    mAttentionList.add(friend);
                } else {//好友和悦聊团队
                    mFriendList.add(friend);
                }
            }
            if (mFriendList.size() > 0) {
                ll_friends.setVisibility(View.VISIBLE);
            } else {
                ll_friends.setVisibility(View.GONE);
            }
            if (mAttentionList.size() > 0) {
                ll_attention.setVisibility(View.VISIBLE);
            } else {
                ll_attention.setVisibility(View.GONE);
            }
            mAdapter.notifyDataSetChanged();
            mAttentionAdapter.notifyDataSetChanged();

        } else {
            clearData();//清除数据
        }

        /*判断列表大小 0则页面显示搜索为空页面*/
        if (mFriendList.size() == 0 && mAttentionList.size() == 0) {
            ll_layout_search_empty.setVisibility(View.VISIBLE);
        } else {
            ll_layout_search_empty.setVisibility(View.GONE);
        }
    }

    private void clearData() {
        mFriendList.clear();
        mAttentionList.clear();
        mAdapter.notifyDataSetChanged();
        mAttentionAdapter.notifyDataSetChanged();
        ll_friends.setVisibility(View.GONE);
        ll_attention.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(String cancle) {
        if (cancle.equals("cancle")) {
            finish();
        }
    }

}
